################################################################################
# Copyright (c) 2011, Anton Babushkin
# All rights reserved.
# 
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of the <organization> nor the
#       names of its contributors may be used to endorse or promote products
#       derived from this software without specific prior written permission.
# 
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
################################################################################

'''MiceCode designed as memory and speed effective alternative to JSON,
optimized for modern object-oriented languages like Python or Java. It's
more powerful than Bencode or BSON, and more effective than JSON. Protocol
ideology influenced by JSON, Bencode, FAST. MiceCode have the following data
types: Integer, Float, Boolean, None, String, Bytes, List, Map. Floats and
integers are stored in the smallest possible representation that doesn't
worse precision. Protocol supports integers and floats up to 128bit and
string/bytes length up to 2^64. This realization limitations: floats up
to 64bits only.'''

__author__	= "Anton Babushkin"
__version__	= "0.5-beta"

import struct, math

_BITS_SPECIAL	= 0x00
_BITS_INTEGER	= 0x10
_BITS_FLOAT		= 0x20
_BITS_BYTES		= 0x30
_BITS_STRING	= 0x40
_BITS_LIST		= 0x50
_BITS_MAP		= 0x60

_BITS_FALSE		= 0x00
_BITS_TRUE		= 0x01
_BITS_NONE		= 0x0F

def decode(bytes):
	return _decodeObject(bytes, 0)[0]

def _decodeObject(bytes, start):
	b = ord(bytes[start])
	t = b & 0xF0
	if t == _BITS_SPECIAL:
		v = b & 0x0F
		if v == _BITS_FALSE:
			return False, start + 1
		elif v == _BITS_TRUE:
			return True, start + 1
		elif v == _BITS_NONE:
			return None, start + 1
	elif t == _BITS_INTEGER:
		return _decodeInteger(bytes, start)
	elif t == _BITS_FLOAT:
		return _decodeFloat(bytes, start)
	elif t == _BITS_BYTES:
		return _decodeBytes(bytes, start)
	elif t == _BITS_STRING:
		return _decodeString(bytes, start)
	elif t == _BITS_LIST:
		return _decodeList(bytes, start)
	elif t == _BITS_MAP:
		return _decodeMap(bytes, start)
	raise Exception("Invalid byte stream: 0x%02x" % t)

def _decodeInteger(bytes, start):
	size = (ord(bytes[start]) & 0x0F) + 1
	res = 0
	for i in xrange(size):
		res |= ord(bytes[start+size-i]) << (i * 8)
	end = start + 1 + size
	if ord(bytes[start+1]) & 0x80 == 0:
		return res, end
	else:
		return res - (1l << (size * 8)), end

def _decodeSize(bytes, start):
	s = ord(bytes[start]) & 0x0f
	if s <= 0x08:
		return s, start + 1
	else:
		assert s & 0x07 <= 4, "Size field bytes number > 4"
		size = s & 0x07
		res = 0
		start += 1
		for i in xrange(size):
			res |= ord(bytes[start+size-1-i]) << (i * 8)
		res += 0x09
		assert res > 0, "Negative size"
		return res, start + size

def _decodeFloat(bytes, start):
	s = ord(bytes[start]) & 0x0f
	if s == 0x03:	# Single presision
		r = 0
		start += 1
		end = start + 4
		assert end <= len(bytes)
		return struct.unpack("!f", bytes[start:end])[0], end
	elif s == 0x07:	# Double presision
		r = 0
		start += 1
		end = start + 8
		assert end <= len(bytes)
		return struct.unpack("!d", bytes[start:end])[0], end
	else:
		raise Exception("Error decoding float, header: 0x%02x" % s);

def _decodeList(bytes, start):
	rv = []
	size, start = _decodeSize(bytes, start)
	for i in xrange(size):
		obj, start = _decodeObject(bytes, start)
		rv.append(obj)
	return rv, start

def _decodeMap(bytes, start):
	rv = {}
	size, start = _decodeSize(bytes, start)
	for i in xrange(size):
		k, start = _decodeString(bytes, start)
		v, start = _decodeObject(bytes, start)
		rv[k] = v
	return rv, start

def _decodeBytes(bytes, start):
	size, start = _decodeSize(bytes, start)
	end = start + size
	return bytes[start:end], end

def _decodeString(bytes, start):
	size, start = _decodeSize(bytes, start)
	end = start + size
	return bytes[start:end].decode("utf8"), end

def encode(obj):
	if obj is None:
		return chr(_BITS_SPECIAL | _BITS_NONE)
	elif obj is False:
		return chr(_BITS_SPECIAL | _BITS_FALSE)
	elif obj is True:
		return chr(_BITS_SPECIAL | _BITS_TRUE)
	elif isinstance(obj, int) or isinstance(obj, long):
		return _encodeInteger(obj)
	elif isinstance(obj, float):
		return _encodeFloat(obj)
	elif isinstance(obj, str):
		return _encodeBytes(obj)
	elif isinstance(obj, unicode):
		return _encodeString(obj)
	elif isinstance(obj, list) or isinstance(obj, tuple) or isinstance(obj, set):
		return _encodeList(obj)
	elif isinstance(obj, dict):
		return _encodeMap(obj)
	raise Exception("Unsupported object type: %s" % type(obj).__name__)

def _encodeSize(size):
	if size <= 0x08:
		res = chr(size)
	else:
		size -= 0x09
		for n in xrange(1, 5):
			if size < (1 << (n * 8)):
				break
		res = chr(0x08 | n) + struct.pack("!I", size)[-n:]
	return res

def _encodeList(c):
	size = _encodeSize(len(c))
	size = chr(ord(size[0]) | _BITS_LIST) + size[1:]
	p = [size]
	for o in c:
		p.append(encode(o))
	return ''.join(p)

def _encodeMap(m):
	size = _encodeSize(len(m))
	size = chr(ord(size[0]) | _BITS_MAP) + size[1:]
	p = [size]
	for k, v in m.iteritems():
		p.append(_encodeString(k))
		p.append(encode(v))
	return ''.join(p)

def _encodeInteger(num):
	if num >= 0:
		abs_num = num
	else:
		abs_num = -1 - num
	for n in xrange(16):	# n == size - 1
		if abs_num < (0x80 << (n * 8)):
			break
	else:
		raise Exception("Too large integer (> 128bits)")
	res = [chr(_BITS_INTEGER | n)]
	if num < 0:
		num -= 0x100 << (n * 8)
	for i in xrange(n, -1, -1):
		res.append(chr((num >> (i * 8)) & 0xFF))
	return ''.join(res)

def _encodeFloat(num):
	p_fnum = struct.pack("!f", num)
	p_dnum = struct.pack("!d", num)
	fnum = struct.unpack("!f", p_fnum)[0]
	dnum = struct.unpack("!d", p_dnum)[0]
	if fnum == dnum or math.isnan(num) or math.isinf(num):
		return chr(_BITS_FLOAT | 0x03) + p_fnum
	else:
		return chr(_BITS_FLOAT | 0x07) + p_dnum

def _encodeBytes(b):
	size = _encodeSize(len(b))
	return chr(ord(size[0]) | _BITS_BYTES) + size[1:] + b

def _encodeString(s):
	b = s.encode("utf8")
	size = _encodeSize(len(b))
	return chr(ord(size[0]) | _BITS_STRING) + size[1:] + b

def _test():
	a = range(-1, 2)
	a.append(-10000000)
	a.append(10000000)
	a.append(0x10000000000000000000000000000000)
	a.append(-0x10000000000000000000000000000000)
	a.append(0x7fffffffffffffffffffffffffffffff)
	a.append(-0x80000000000000000000000000000000)
	a.append(0.0)
	a.append(1.0)
	a.append(-1.0)
	a.append("Hello")
	a.append(u"Hello")
	a.append({
		u"AAA": 0.0,
		u"BBB": 1.0,
		u"CCC": 3423423424.238432784723
	})
	print a
	b = encode(a)
	for i in b:
		print "%02x" % ord(i),
	print
	c = decode(b)
	print c
	print len(b)
	print "OK:", a == c

if __name__ == "__main__":
	_test()
